package com.agriculture.monitoring.repository;

import com.agriculture.monitoring.entity.GeoPathPoint;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface PathPointRepository extends JpaRepository<GeoPathPoint, Long> {
    
    List<GeoPathPoint> findByDeviceIdOrderByRecordTime(Long deviceId);
    
    List<GeoPathPoint> findByPathIdOrderByRecordTime(Long pathId);
    
    @Query("SELECT p FROM GeoPathPoint p WHERE p.device.id = :deviceId AND " +
           "p.recordTime BETWEEN :startTime AND :endTime ORDER BY p.recordTime")
    List<GeoPathPoint> findByDeviceIdAndTimeRange(@Param("deviceId") Long deviceId,
                                                 @Param("startTime") LocalDateTime startTime,
                                                 @Param("endTime") LocalDateTime endTime);
    
    @Query(value = "SELECT * FROM geo_path_point WHERE device_id = :deviceId AND " +
            "record_time >= :startTime AND record_time <= :endTime " +
            "ORDER BY record_time LIMIT :limit", nativeQuery = true)
    List<GeoPathPoint> findRecentPoints(@Param("deviceId") Long deviceId,
                                       @Param("startTime") LocalDateTime startTime,
                                       @Param("endTime") LocalDateTime endTime,
                                       @Param("limit") Integer limit);
}